#pragma once

#include "ferryfs.h"
#include "utils.h"
#include "ferrylog.h"
#include <QDebug>
#include <QStorageInfo>
#include <QJsonObject>
#include <QVariantMap>
#include "SM4.h"
#include "AuditPlanFun.h"
#include <QHostAddress>
#include <qnetworkinterface.h>
#include "curl.h"
#include <QtSql/QSqlQuery>
#include <QCoreApplication>


Ferryfs* ferryfs;

Ferryfs::Ferryfs(QString mountpoint)
{
    this->mountpoint = mountpoint;
    ferryfs = this;
}

bool Ferryfs::connectUdiskDB(QString connection)
{
    ferryLog->m_db = QSqlDatabase::addDatabase("QSQLITE" , connection);
    ferryLog->m_db.setDatabaseName(this->mountpoint + "/.db/ferrylog");
    // 打开数据库
    if (!ferryLog->m_db.open()) {
        qDebug() << "Error: Failed to connect database" << ferryLog->m_db.lastError().text();
        return false;
    } else {
        qDebug() << "Database in upan connected successfully";
        return true;
    }
}

bool Ferryfs::connectBuildDB(QString connection)
{
    ferryLog->m_db = QSqlDatabase::addDatabase("QSQLITE" , connection);
    ferryLog->m_db.setDatabaseName(QCoreApplication::applicationDirPath() + "/db/ferrylog");
    // 打开数据库
    if (!ferryLog->m_db.open()) {
        qDebug() << "Error: Failed to connect database" << ferryLog->m_db.lastError().text();
        return false;
    } else {
        qDebug() << "Database in build/ connected successfully";
        return true;
    }
}

void Ferryfs::closeDB()
{
    ferryLog->m_db.close();
}

unsigned int* Ferryfs::qByteArrayToUnsignedInt(QByteArray source)
{
    QByteArray byteArray = source;
    const char* data = byteArray.constData();
    int dataSize = byteArray.size() / sizeof(unsigned int);
    unsigned int* unsignedData = new unsigned int[dataSize];
    memcpy(unsignedData, data, byteArray.size());
    //    for (int i = 0; i < dataSize; i++) {
    //            unsigned int value = unsignedData[i];
    //            qDebug() << "unsigned int at index" << i << ": " << value;
    //        }
    //    // 使用unsignedData数组进行后续操作
    return unsignedData;
}

QByteArray Ferryfs::unsignedIntToQByteArray(unsigned int* des, int datasize)
{
    const unsigned int* unsignedData = des;
    int dataSize = /* 数据的长度 */datasize;

    // 将 unsignedData 封装到 QByteArray 中
    QByteArray byteArray(reinterpret_cast<const char*>(unsignedData), dataSize);

    return byteArray;
}

QString Ferryfs::readDeviceIDFromDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    QString tableName = "usb_id";
    QVariant result = ferryLog->queryAllLog(tableName);
    QVariantList resultList = result.toList();
#ifndef QT_NO_DEBUG
    qDebug() << resultList;
#endif
    int lastIndex = resultList.size() - 1;
    QVariant lastItem = resultList[lastIndex];
    QVariantMap lastMap = lastItem.toMap(); // 将QVariant转换为QVariantMap
    //    QByteArray value;
    auto it = lastMap.constEnd() - 1;
    const QString key = it.key();
    const QByteArray value = it.value().toByteArray();
#ifndef QT_NO_DEBUG
    qDebug() << "Key: " << key << " Value: " << value;
#endif
    //    QString encodedInfo = value.toString();
    const QByteArray decodedInfo = decryptQByteArray(value);
    const QString deviceid = QString::fromLatin1(decodedInfo);
#ifndef QT_NO_DEBUG
    qDebug() << "QString DeviceID:" << decodedInfo;
#endif
    return decodedInfo;
}

void Ferryfs::writeDeviceIDToDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__ ;
#endif


    const QString tableName = "usb_id";
    const QString randomString = Utils::generateRandomString(12);
#ifndef QT_NO_DEBUG
    qDebug() << "randomString:" << randomString;
#endif

    //    QByteArray byteArray  = randomString.toLatin1();
    //    QByteArray encodeInfo = encryptQByteArray(byteArray);
    const QByteArray encodeInfo = encryptQByteArray(randomString.toLatin1());
    QVariantMap log;
    log.insert("usb_id", encodeInfo);
    ferryLog->removeAllRecord(tableName);
    ferryLog->addFerryLog(log, tableName);

}

QString Ferryfs::readPasswordFromDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif

    QString tableName = "usb_password";
    QVariant result = ferryLog->queryAllLog(tableName);
    QVariantList resultList = result.toList();
    int lastIndex = resultList.size() - 1;
    QVariant lastItem = resultList[lastIndex];
    QVariantMap lastMap = lastItem.toMap(); // 将QVariant转换为QVariantMap
    QVariant value;
    auto it = lastMap.constEnd() - 1;
    QString key = it.key();
    value = it.value();
#ifndef QT_NO_DEBUG
    qDebug() << "Key: " << key << " Value: " << value;
#endif

    const QByteArray decodedInfo = decryptQByteArray(value.toByteArray());
    const QString ret = QString::fromLatin1(decodedInfo);
    qDebug() << "password" << ret;
    return ret;
}

void Ferryfs::writePasswordToDB(const QString password)
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__ ;
#endif
    QString tableName = "usb_password";
    const QByteArray encodeInfo = encryptQByteArray(password.toLatin1());
    QVariantMap log;
    log.insert("usb_password", encodeInfo);
    ferryLog->removeAllRecord(tableName);
    ferryLog->addFerryLog(log, tableName);
}

void Ferryfs::writeKeyToDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__ ;
#endif

    //QString key = Utils::generateRandomString(8);
    //QString key = "30GTWPCS";
    unsigned char MK[16];
    memset((unsigned char *)MK, 0, 16);
    Utils::generateRandomUnsignedChar(MK, 8);
    memset((unsigned char *)MK + 8, 0, 8);
    unsigned int rk[32];
    memset(rk, 0, sizeof(unsigned int) * 32);
    SM4_KeySchedule((unsigned char*)MK, rk);
    const QByteArray encodedInfo = unsignedIntToQByteArray(rk, 128);

    QString tableName = "key";
    QVariantMap log;
    log.insert("key", encodedInfo);
    ferryLog->removeAllRecord(tableName);
    ferryLog->addFerryLog(log, tableName);
}


unsigned int* Ferryfs::readKeyFromDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif

    QString tableName = "key";
    QVariant result = ferryLog->queryAllLog(tableName);
    QVariantList resultList = result.toList();
    int lastIndex = resultList.size() - 1;
    QVariant lastItem = resultList[lastIndex];
    QVariantMap lastMap = lastItem.toMap(); // 将QVariant转换为QVariantMap
    QByteArray value;
    auto it = lastMap.constEnd() - 1;
    QString key = it.key();
    value = it.value().toByteArray();

    //    QString base64EncodedKey = value.toString();
    //    // 进行Base64解码
    //    QByteArray byteArray = QByteArray::fromBase64(base64EncodedKey.toUtf8());
    //    QString decodedInfo = QString::fromUtf8(byteArray.constData(), byteArray.size());

    unsigned int* ret = qByteArrayToUnsignedInt(value);

    return ret;
}

bool Ferryfs::writeAuditInfoToDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif

    QByteArray usbnumber = encryptQByteArray(readDeviceIDFromDB().toLatin1());
    QByteArray readcount = encryptQByteArray(QString("1").toLatin1());
    QByteArray writecount = encryptQByteArray(QString("1").toLatin1());
    QByteArray insertionTime = encryptQByteArray(getTime().toLatin1());
    QByteArray lastreadtime = insertionTime;
    QByteArray lastwritetime = insertionTime;
    QByteArray areaid = encryptQByteArray(QString("1").toLatin1());
    QByteArray userid = encryptQByteArray(QString("1").toLatin1());
    QByteArray removaltime = insertionTime;
    QByteArray installedsp = encryptQByteArray(QString("1").toLatin1());
    QByteArray deptid = encryptQByteArray(QString("205").toLatin1());
    QByteArray nickname = encryptQByteArray(QString("ruoyi").toLatin1());
    QByteArray departmentname = encryptQByteArray(QString("chengyang").toLatin1());
    QByteArray areaname = encryptQByteArray(QString("qingdaodanwei").toLatin1());
    QByteArray macIp = encryptQByteArray(this->getMac().toLatin1());
    QByteArray computerIp = encryptQByteArray(this->getIp().toLatin1());

    QString sql = "INSERT INTO eu_usb_info (usb_number, readCount, writeCount, lastReadTime, lastWriteTime, area_id, user_id, insertionTime, removalTime, computerIp, installedSP, dept_id, macIp, nick_name, department_name, area_name) "
                  "VALUES (:usb_number, :read_count, :write_count, :last_read_time, :last_write_time, :area_id, :user_id, :insertion_time, :removal_time, :computer_ip, :installed_sp, :dept_id, :mac_ip, :nick_name, :department_name, :area_name)";

    QSqlQuery query(ferryLog->m_db);
    query.prepare(sql);
    query.bindValue(":usb_number", usbnumber);
    query.bindValue(":read_count", readcount);
    query.bindValue(":write_count", writecount);
    query.bindValue(":last_read_time", lastreadtime);
    query.bindValue(":last_write_time", lastwritetime);
    query.bindValue(":area_id", areaid);
    query.bindValue(":user_id", userid);
    query.bindValue(":insertion_time", insertionTime);
    query.bindValue(":removal_time", removaltime);
    query.bindValue(":computer_ip", computerIp);
    query.bindValue(":installed_sp", installedsp);
    query.bindValue(":dept_id", deptid);
    query.bindValue(":mac_ip", macIp);
    query.bindValue(":nick_name", nickname);
    query.bindValue(":department_name", departmentname);
    query.bindValue(":area_name", areaname);

    if(query.exec()) {
#ifndef QT_NO_DEBUG
        qDebug()<<"insert eu_usb_info success!";
#endif \
        //fl.m_db.close();
        return true;
    } else {
        //fl.m_db.close();
        return false;
    }
}

bool Ferryfs::readAuditInfoFromDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    QString tableName = "eu_usb_info";
    QVariant result = ferryLog->queryAllLog(tableName);
    QVariantList resultList = result.toList();

    for(int i = 0; i < resultList.size(); i++) {
        QVariant infoItem = resultList[i];
        QVariantMap infoMap = infoItem.toMap();
        for(auto info = infoMap.constBegin(); info != infoMap.constEnd(); ++info) {
            QString key = info.key();
            QVariant varValue = info.value();

            QByteArray encodedInfo = varValue.toByteArray();
            if(encodedInfo.isEmpty()){
                continue;
            }
            const QByteArray value = decryptQByteArray(encodedInfo);
            const QString decodedInfo = QString::fromLatin1(value);
#ifndef QT_NO_DEBUG
            qDebug() << "resultList" << "[" << i << "]" << "   Key: " << key << " Value: " << decodedInfo;
#endif
        }
    }
    return true;
    //     int lastIndex = resultList.size() - 1;
    //     QVariant lastItem = resultList[lastIndex];
    //     // QVariant firstItem = resultList[1];
    //     QVariantMap lastMap = lastItem.toMap(); // 将QVariant转换为QVariantMap
    //     QVariant value;
    //     auto it = lastMap.constEnd() - 1;
    //     QString key = it.key();
    //     value = it.value();
    // #ifndef QT_NO_DEBUG
    //     qDebug() << "Key: " << key << " Value: " << value;
    // #endif
    //     QString encodedInfo = value.toString();
    //     QString ret = decryptQString(encodedInfo);
    //     qDebug() << "ret" << ret;
    //     return true;
}

bool Ferryfs::readAllAuditInfoFromDB()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    QString tableName = "eu_usb_info";
    QVariant result = ferryLog->queryAllLog(tableName);
    QVariantList resultList = result.toList();

    QString usbNumber ;
    QString readCount ;
    QString writeCount ;
    QString insertionTime;
    QString lastreadtime;
    QString lastwriteTime;
    QString areaID ;
    QString userID ;
    QString removalTime;
    QString installedSP ;
    QString deptID ;
    QString departmentName ;
    QString areaName ;
    QString macIp ;
    QString computerIp ;

    QMap<QString, QString*> fieldMap;
    fieldMap["usb_number"] = &usbNumber;
    fieldMap["readCount"] = &readCount;
    fieldMap["writeCount"] = &writeCount;
    fieldMap["insertionTime"] = &insertionTime;
    fieldMap["lastReadTime"] = &lastreadtime;
    fieldMap["lastWriteTime"] = &lastwriteTime;
    fieldMap["area_id"] = &areaID;
    fieldMap["user_id"] = &userID;
    fieldMap["removalTime"] = &removalTime;
    fieldMap["installedSP"] = &installedSP;
    fieldMap["dept_id"] = &deptID;
    fieldMap["department_name"] = &departmentName;
    fieldMap["area_name"] = &areaName;
    fieldMap["macIp"] = &macIp;
    fieldMap["computerIp"] = &computerIp;

    for(int i = 0; i < resultList.size(); i++) {
        QVariant infoItem = resultList[i];
        QVariantMap infoMap = infoItem.toMap();

        for(auto info = infoMap.constBegin(); info != infoMap.constEnd(); ++info) {
            QString key = info.key();
            if(fieldMap.contains(key)){
                QByteArray encodedInfo = info.value().toByteArray();
                if(encodedInfo.isEmpty()){
                    continue;
                }
                QString value = QString::fromLatin1(decryptQByteArray(encodedInfo));
#ifndef QT_NO_DEBUG
                qDebug() << "resultList" << "[" << i << "]" << "   Key: " << key << " Value: " << value;
#endif
                *(fieldMap.value(key)) = value;
            }
        }
        qDebug()<<"df ";
        PostAuditInfo(*(fieldMap.value("usb_number")), (*(fieldMap.value("readCount"))).toInt(), (*(fieldMap.value("writeCount"))).toInt(), *(fieldMap.value("insertionTime")), *(fieldMap.value("lastReadTime")), *(fieldMap.value("lastWriteTime")), (*(fieldMap.value("area_id"))).toInt(), (*(fieldMap.value("user_id"))).toInt(), *(fieldMap.value("removalTime")), (*(fieldMap.value("installedSP"))).toInt(), (*(fieldMap.value("dept_id"))).toInt(), *(fieldMap.value("department_name")), *(fieldMap.value("area_name")), *(fieldMap.value("macIp")), *(fieldMap.value("computerIp")));
    }
    ferryLog->removeAllRecord(tableName);
    return true;
}

QString Ferryfs::getIp()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    QString strIpAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // 获取第一个本主机的IPv4地址
    int nListSize = ipAddressesList.size();
    for (int i = 0; i < nListSize; ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            strIpAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // 如果没有找到，则以本地IP地址为IP
    if (strIpAddress.isEmpty())
        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
    // string ret = strIpAddress.toStdString();

    return strIpAddress;
}

QString Ferryfs::getMac()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    // string ret = strMacAddr.toStdString();

    return strMacAddr;
}

QString Ferryfs::getTime()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    time_t timep;
    time(&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
    QString time = QString(tmp);
    return time;
}


bool Ferryfs::createFerryfs(const QString &path)
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__ ;
#endif
    ferryLog->isSqliteCipherLoaded();

    QString usbPath = Utils::getDeviceMountpoint(path);

    QString filename = usbPath;

    QString sourcePath = ferryLog->getDataBasePath()+"/"+ferryLog->getDbName();
    QString destinationPath;

    QFile sourceFile(sourcePath);
    if(!sourceFile.exists()) {
#ifndef QT_NO_DEBUG
        qDebug() << "源文件不存在" << sourcePath;
#endif
        return false;
    }

    int lastSlashIndex = sourcePath.lastIndexOf('/');
    if(lastSlashIndex != -1) {
        filename = sourcePath.mid(lastSlashIndex + 1);
#ifndef QT_NO_DEBUG
        qDebug() <<  "filename:" << filename ;
#endif
    }

    destinationPath = usbPath + "/.db/" + filename;
#ifndef QT_NO_DEBUG
    qDebug() << "destinationPath" << destinationPath ;
#endif
    QFile destinationFile(destinationPath);

    QFileInfo fileInfo(destinationPath);
    QDir().mkpath(fileInfo.absolutePath());

    if (!destinationFile.open(QIODevice::ReadWrite | QIODevice::Unbuffered)) {
#ifndef QT_NO_DEBUG
        qDebug() << "Error opening file: " << destinationFile.errorString();
        qDebug() << "无法打开目的文件" << destinationPath;
#endif
        return false;
    }
    destinationFile.close();

    //    writeDeviceIDToDB();

    if (sourceFile.open(QIODevice::ReadOnly) && destinationFile.open(QIODevice::WriteOnly)) {
        QByteArray fileData = sourceFile.readAll();
        qint64 bytesWritten = destinationFile.write(fileData);

        if (bytesWritten != -1) {
#ifndef QT_NO_DEBUG
            qDebug() << "成功移动文件: " << sourcePath << " 到: " << destinationPath;
#endif
        } else {
#ifndef QT_NO_DEBUG
            qDebug() << "移动文件" << sourcePath << " 到: " << destinationPath << "失败";
#endif
            return false;
        }
    } else {
#ifndef QT_NO_DEBUG
        qDebug() << "无法打开源文件或目标文件";
#endif
        return false;
    }

    sourceFile.close();
    destinationFile.close();

    return true;
}

const bool Ferryfs::isFerryfs(const QString &path)
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__ ;
#endif
    QString directoryPath = path + "/.db";

    QDir directory(directoryPath);
    if(directory.exists()) {
#ifndef QT_NO_DEBUG
        qDebug() << ".db Directory exists";
#endif
        return true;
    } else {
#ifndef QT_NO_DEBUG
        qDebug() << ".db Directory does not exist";
#endif
        return false;
    }
}

QString Ferryfs::getDefaultPassword()
{
#ifndef QT_NO_DEBUG
    qDebug() << Q_FUNC_INFO << __LINE__;
#endif
    return "6aR1fCpV6D2zKbq8sXgOeNlT7hWt3yJvZ9UoM5dYxGwQ0iLrHpAjE6uBnS2cF5a3";
}

const QByteArray Ferryfs::encryptQByteArray(const QByteArray &plaintext)
{
    // 计算需要填充的字节数
    const int padding_length = (plaintext.size() % 16);
    unsigned char pucPaddingData[16];


    QByteArray ret;
    const int sizeOfPer16 = 16;
    const unsigned int* rk = readKeyFromDB();

    for(int i = 0; i < plaintext.size(); i += 16){
        unsigned char* PlainText = (unsigned char *)plaintext.constData() + i;
        unsigned char  CipherText[16];
        if(plaintext.size() - i < 16){
            PKCS7((unsigned char *)PlainText, padding_length, pucPaddingData);
            PlainText = pucPaddingData;
        }
        SM4_Encrypt((unsigned int*)rk, PlainText, CipherText);
        ret.append((const char *)CipherText, 16);
    }
    delete [] rk;
    return ret;
}

const QByteArray Ferryfs::decryptQByteArray(const QByteArray &ciphertext)
{
    QByteArray ret;
    const int sizeOfPer16 = 16;
    const unsigned int* rk = readKeyFromDB();

    for(int i = 0 ; i < ciphertext.size(); i += 16){
        unsigned char* CipherText = (unsigned char*)ciphertext.constData() + i;
        unsigned char PlainText[sizeOfPer16];
        SM4_Decrypt((unsigned int*)rk, CipherText, PlainText);
        ret.append((const char*)PlainText, 16);
    }

    QChar lastChar = ret.at(ret.length() - 1);
    int lastValue = lastChar.unicode();
    int paddingsize = lastValue;
    int num = 0;
    for(int i = ret.size() - 1 ; i >= 0; i--){
        if(ret.at(i) == lastValue){
            num++;
        } else {
            break;
        }
    }

    if(num == paddingsize){
        ret = ret.left(ret.length() - paddingsize);
    }

    return ret;
}


int Ferryfs::PKCS7(unsigned char *pucData, unsigned long ulDataLen, unsigned char pucPaddingData[16])
{
    unsigned char pucPadding = 0;

    if(ulDataLen > 16)
    {
        return -1;
    }
    pucPadding = 16 - ulDataLen;

    memcpy(pucPaddingData, pucData, ulDataLen);
    memset(pucPaddingData + ulDataLen, pucPadding, 16 - ulDataLen);
    return 0;
}

size_t getLoginData1(void *contents, size_t size, size_t nmemb, void *response)
{
    std::string *str = (std::string*)response;
    (*str).append((char*)contents,size*nmemb);

    return size*nmemb;
}

bool Ferryfs::PostAuditInfo(QString usbnumber, int readcount, int writecount, QString insertiontime, QString lastreadtime, QString lastwritetime, int areaid, int userid, QString removaltime, int installedsp, int deptid, QString departmentname, QString areaname, QString macip, QString computerip)
{
    CURL *curl = nullptr;
    CURLcode res;
    std::string response="";
    curl = curl_easy_init();
    QString ipaddress = getIpAddress();
    if (curl)
    {
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type:application/json");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        char json[1024];

        std::string usbNumber = usbnumber.toStdString();
        int readCount = readcount;
        int writeCount = writecount;
        std::string insertionTime = insertiontime.toStdString();
        std::string lastreadTime = lastreadtime.toStdString();
        std::string lastwriteTime = lastwritetime.toStdString();
        int areaID = areaid;
        int userID = userid;
        std::string removalTime = removaltime.toStdString();
        int installedSP = installedsp;
        int deptID = deptid;
        std::string departmentName = departmentname.toStdString();
        std::string areaName = areaname.toStdString();
        std::string macIp = macip.toStdString();
        std::string computerIp = computerip.toStdString();

        snprintf(json, sizeof(json),
                 "{\"usbNumber\":\"%s\",\"readCount\":%d,\"writeCount\":%d,\"insertionTime\":\"%s\",\"lastReadTime\":\"%s\",\"lastWriteTime\":\"%s\",\"areaId\":%d,\"userId\":%d,\"removalTime\":\"%s\",\"installedSP\":%d,\"deptId\":%d,\"deptName\":\"%s\",\"areaName\":\"%s\",\"macIp\":\"%s\",\"computerIp\":\"%s\",\"isCommon\":%d}",
                 usbNumber.c_str(), readCount, writeCount, insertionTime.c_str(), lastreadTime.c_str(), lastwriteTime.c_str(), areaID, userID, removalTime.c_str(), installedSP, deptID, departmentName.c_str(), areaName.c_str(), macIp.c_str(), computerIp.c_str(), 0);
        qDebug() << json;
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);            // 指定post内容
        QString url = "http://" + ipaddress + "/system/usbInfo";
        curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); // 指定url

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getLoginData1);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            std::cout <<"code0:"  << std::endl;
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return false;
        }
        curl_easy_cleanup(curl);
    }
    std::string code = response.substr(response.length()-4, 3);
    std::cout << "code:" << code << std::endl;
    if(code == "200")return true;
    return false;
}

QString Ferryfs::getConfigIpAddress(){
    return getIpAddress();
}

QString Ferryfs::getIpAddress()
{
    QString ip = "127.0.0.1";
    QFile file("ip.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "无法打开文件";

    }
    QTextStream in(&file);
    while (!in.atEnd())
    {
        ip = in.readLine();  // 逐行读取数据
        qDebug() << ip;
    }
    return ip;
    file.close();
}


